package com.ktjiaoyu.ktmall.service.impl;

import com.ktjiaoyu.ktmall.dao.CategoryDao;
import com.ktjiaoyu.ktmall.dao.impl.CategoryDaoImpl;
import com.ktjiaoyu.ktmall.entity.Category;
import com.ktjiaoyu.ktmall.service.CategoryService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xm
 * @date 2025/9/10
 * @Dome
 */
public class CategoryServiceImpl implements CategoryService {
    CategoryDao categoryDao = new CategoryDaoImpl();

    @Override
    public List<Category> findAll() {
        return categoryDao.findAll();
    }

    @Override
    public List<Category> findTree() {
        List<Category> all = categoryDao.findAll();
        return buildTree(all, "0");
    }

    private List<Category> buildTree(List<Category> all, String parentId) {
        List<Category> tree = new ArrayList<Category>();
        for (Category category : all) {
            if (category.getParentId() != null && category.getParentId().equals(parentId)) {
                List<Category> children = buildTree(all, category.getId());
                category.setChildren(children);
                tree.add(category);
            }
        }
        return tree;
    }

    @Override
    public int insert(Category category) {
        return categoryDao.insert(category);
    }

    @Override
    public int update(Category category) {
        return categoryDao.update(category);
    }

    @Override
    public boolean saveOrUpdate(Category category) {
        if (category.getId() == null) {
            return categoryDao.insert(category) == 1;
        } else {
            return categoryDao.update(category) == 1;
        }
    }

    @Override
    public boolean removeById(Long id) {
        return categoryDao.delete(id) > 0;
    }
}
